<template>
    <el-container style="height: 950px; border: 1px solid #eee">
        <el-aside width="350px" >
            <el-container >
                <!--   患者选择区      -->
                <el-header style="padding: 0;margin: 0">
                    <el-row>
                        <el-col :span="21" style="text-align: left">
                            <el-tag>患者选择：</el-tag>
                        </el-col>
                        <el-col :span="3" style="text-align: right">
                            <el-button type="primary"  size="small" @click="reloadUser" style="margin-right: 5px">
                                <el-icon><Refresh/></el-icon>
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-input placeholder="请输入内容" v-model="inputPatient"  style="width: 100%">
                            <template #prepend>
                                患者名：
                            </template>
                            <template #append>
                                <el-icon><Search/></el-icon>
                            </template>
                        </el-input>

                    </el-row>
                </el-header>
                <el-main style="height: 800px;padding: 0;margin: 0">
                    <el-tabs type="border-card" >
                        <el-tab-pane label="本人" >
                            <el-tag size="small" >未诊患者：</el-tag>
                            <el-table ref="singleTable" :data="filteredUndiagnosedPatients" highlight-current-row 
                            @row-dblclick = "handleDBCurrentChange"
                                      style="width: 100%;height: 50%" :show-header="false" max-height="400" size="small">
                                <el-table-column property="CaseNumber" label="病历号" width="80">
                                </el-table-column>
                                <el-table-column property="RealName" label="姓名" >
                                </el-table-column>
                                <el-table-column property="Age" label="年龄" width="50">
                                </el-table-column>
                            </el-table><br/><br/>
                            <el-tag size="small" >已诊患者：</el-tag>
                            <el-table ref="singleTable" :data="filteredDiagnosedPatients" 

                            @row-dblclick = "handleDBCurrentChange"
                                      style="width: 100%;height: 50%" :show-header="false" size="small">
                                <el-table-column property="CaseNumber" label="病历号" width="80">
                                </el-table-column>
                                <el-table-column property="RealName" label="姓名" >
                                </el-table-column>
                                <el-table-column property="Age" label="年龄" width="50">
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="科室*">
                            <el-tag>未诊患者：</el-tag>

                            <el-table ref="singleTable" :data="filtereddeptUndiagnosedPatients" highlight-current-row
                            
                                      style="width: 100%;height: 50%" :show-header="false" size="small">
                                <el-table-column property="CaseNumber" label="病历号" width="80">
                                </el-table-column>
                                <el-table-column property="RealName" label="姓名" >
                                </el-table-column>
                                <el-table-column property="Age" label="年龄" width="50">
                                </el-table-column>
                            </el-table>
                            <el-tag>已诊患者：</el-tag>
                            <el-table ref="singleTable" :data="filtereddeptDiagnosedPatients"
                                      style="width: 100%;height: 50%" :show-header="false" size="small">
                                <el-table-column property="CaseNumber" label="病历号" width="80">
                                </el-table-column>
                                <el-table-column property="RealName" label="姓名" >
                                </el-table-column>
                                <el-table-column property="Age" label="年龄" width="50">
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-main>
            </el-container>
        </el-aside>

        <el-container direction="vertical" style="height: 950px">
            <el-row>

                <span style="margin-left: 20px;font-size: small;" :span="20">{{showPatientsTop}}</span>
                <el-button type="text" size="small" style="float: right;margin-right: 20px;" @click="endRegister" v-if="showStop" :span="2">诊毕</el-button>

            </el-row>

            
            <el-tabs type="border-card" :before-leave="toTab">
                <!-- 患者检查填写  -->
                <el-tab-pane label="病历首页">
                    <!-- 1. 门诊病历 -->
                    <el-container v-loading="loading">


                        <!-- 页面正文 -->
                        <el-main style="width:100%;background:#fff;height:800px;overflow-y: auto">
                            <el-form ref="form" :model="medicalRecord01" label-width="80px" label-position="left" size="small" >
                                <el-row style="background-color: #EAF1F5;margin-top: -20px">
                                    <el-col :span="8" style="margin-top: 4px;">

                                    </el-col>
                                    <el-col :span="4" >
                                        <el-button type="text" size="small"  @click="stageCheck">暂存</el-button>
                                    </el-col>
                                    <el-col :span="4" >
                                        <el-button type="text" size="small"  @click="saveCheck">提交</el-button>
                                    </el-col>
                                    <el-col :span="4" >
                                        <el-button type="text" size="small"  :disabled="isSaved" @click="cleanCheck">清空所有</el-button>
                                    </el-col>
                                    <el-col :span="4" >
                                        <el-button type="text" size="small"  @click="refMedicalRecord">刷新</el-button>
                                    </el-col>
                                </el-row>
                                <el-tag>病史内容：</el-tag>
                                <el-form-item label="主诉">
                                    <el-input type="textarea" :rows="1" v-model="medicalRecord01.readme"></el-input>
                                </el-form-item>
                                <el-form-item label="现病史">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.present" ></el-input>
                                </el-form-item>
                                <el-form-item label="现病治疗情况">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.presenttreat" ></el-input>
                                </el-form-item>
                                <el-form-item label="既往史">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.history"></el-input>
                                </el-form-item>
                                <el-form-item label="过敏史">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.allergy" ></el-input>
                                </el-form-item>
                                <el-form-item label="体格检查">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.physique"></el-input>
                                </el-form-item>
                                <el-form-item label="诊断">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.diagnosis"></el-input>
                                </el-form-item>

                                <el-form-item label="检查建议">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.proposal" ></el-input>
                                </el-form-item>
                                <el-form-item label="注意事项">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.careful" ></el-input>
                                </el-form-item>
                            </el-form>
                            <el-button type="text" size="small"  @click="saveCheck">提交</el-button>
                        </el-main>

                    </el-container>
                </el-tab-pane>
                <!-- 医生给患者根据病历要求患者进行的检查项：一般无比对标准，如B超 -->
                <el-tab-pane label="检查申请" :lazy="true">

                </el-tab-pane>
                <!-- 医生给患者根据病历要求患者进行的检验项：一般有比对标准，如血常规 -->
                <el-tab-pane label="检验申请*" :lazy="true">
                    <div  >
                        <!-- 3.检验申请 -->
                        <el-container direction="horizontal">
                            <!-- 页面弹窗 -->
                            <el-dialog
                                    title="新增检验申请"
                                    :visible.sync="dialog01Visible"
                                    width="30%">
                                <el-form size="small">
                                    <el-form-item>
                                        <el-input placeholder="请输入内容"   style="width: 100%">
                                            <template slot="prepend">检验名称：</template>
                                            <el-button slot="append" icon="el-icon-search"></el-button>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-table border :data="tableData02" size="small">
                                            <el-table-column prop="choose02" label="" width="30px">
                                                <template slot-scope="scope">
                                                    <input type="radio" name="chooseOne02" />
                                                </template>
                                            </el-table-column>
                                            <el-table-column property="feilei" label="分类" width="80">
                                            </el-table-column>
                                            <el-table-column property="xiangmu" label="项目" >
                                            </el-table-column>
                                        </el-table>
                                    </el-form-item>
                                    <el-form-item label="检验科室" >
                                        <el-select  placeholder="请选择">
                                            <el-option
                                                    v-for="item in selectData01"
                                                    :key="item.keshi"
                                                    :label="item.keshi"
                                                    :value="item.keshi">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="是否加急：" >
                                        <el-switch
                                                v-model="switch01"
                                                active-color="#13ce66">
                                        </el-switch>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="dialog01Visible = false">确 定</el-button>
                                        <el-button @click="dialog01Visible = false">取 消</el-button>
                                    </el-form-item>
                                </el-form>
                            </el-dialog>


                            <!-- 页面正文 -->
                            <el-aside  style="width: 700px;height: 500px;">

                                <el-row style="background-color: #EAF1F5">
                                    <el-col :span="8" style="margin-top: 4px;">
                                        <el-tag size="small">本项目金额合计：</el-tag>
                                        <el-tag type="warning" size="small">235.00元</el-tag>
                                    </el-col>
                                    <el-col :span="3"><el-button type="text" size="small"  @click="dialog01Visible=true">新增项目</el-button></el-col>
                                    <el-col :span="3"><el-button type="text" size="small"  @click="showConfirm('删除选择的检验项目')">删除项目</el-button></el-col>
                                    <el-col :span="2"><el-button type="text" size="small"  @click="showConfirm('使科室收到开立的检验项目')">开立</el-button></el-col>

                                </el-row>

                                <el-form ref="form"  label-width="80px">
                                    <el-row>
                                        <el-col :span="2" style="margin-top: 40px;">
                                            <el-input type="textarea" :rows="4" :disabled="true" style="width: 45px;" v-model="msg01">

                                            </el-input>
                                        </el-col>
                                        <el-col :span="22" style="margin-top: 4px;">
                                            <el-table ref="singleTable" :data="tableData02"
                                                      style="width: 100%;margin: 0px;padding: 0px;" :show-header="true">
                                                <el-table-column  type="selection">
                                                </el-table-column>
                                                <el-table-column property="feilei" label="分类" width="80">
                                                </el-table-column>
                                                <el-table-column property="xiangmu" label="项目" >
                                                </el-table-column>
                                                <el-table-column property="keshi" label="执行科室" width="80">
                                                </el-table-column>
                                                <el-table-column property="jiaji" label="加急" width="50">
                                                </el-table-column>
                                                <el-table-column property="zhuangtai" label="状态" width="80">
                                                </el-table-column>
                                                <el-table-column property="danjia" label="单价" width="80">
                                                </el-table-column>
                                                <el-table-column property="jieguo" label="检验结果" width="80">
                                                    <template slot-scope="scope">
                                                        <el-popover
                                                                placement="right"
                                                                width="400"
                                                                trigger="click">
                                                            <img src=""></img>
                                                            <el-button slot="reference" type="text" size="small">查看</el-button>
                                                        </el-popover>

                                                    </template>
                                                </el-table-column>

                                            </el-table>
                                        </el-col>
                                    </el-row>

                                    <el-row>
                                        <el-form-item label="目的要求">
                                            <el-input type="textarea" :rows="4" placeholder="【检验目的：】【患者主诉：】【现病史：】"></el-input>
                                        </el-form-item>
                                    </el-row>

                                </el-form>
                            </el-aside>
                            <el-main style="margin-top: -20px;">
                                <el-tabs type="card" v-model="activeName">


                                </el-tabs>
                            </el-main>
                        </el-container>

                    </div>
                </el-tab-pane>
                <!-- 患者病历填写  -->
                <el-tab-pane label="门诊确诊*" :lazy="true">

                </el-tab-pane>


            </el-tabs>
        </el-container>
        
    </el-container>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'

// 患者数据
const allPatients = ref([])
const allPatients2 = ref([])
const inputPatient = ref('')

// 计算属性：筛选未诊患者
const filteredUndiagnosedPatients = computed(() => {
    return allPatients.value
        .filter(p => p.Visitstate == 1)  // 使用 == 而不是 === 以防数据类型不一致
        .filter(p => inputPatient.value ? p.RealName.includes(inputPatient.value) : true)
      
})

// 计算属性：筛选已诊患者
const filteredDiagnosedPatients = computed(() => {
    return allPatients.value
        .filter(p => p.Visitstate == 2)
        .filter(p => inputPatient.value ? p.RealName.includes(inputPatient.value) : true)
       
})


// 计算属性：筛选未诊患者
const filtereddeptUndiagnosedPatients = computed(() => {
    return allPatients2.value
        .filter(p => p.Visitstate == 1)  // 使用 == 而不是 === 以防数据类型不一致
        .filter(p => inputPatient.value ? p.RealName.includes(inputPatient.value) : true)
      
})

// 计算属性：筛选已诊患者
const filtereddeptDiagnosedPatients = computed(() => {
    return allPatients2.value
        .filter(p => p.Visitstate == 2)
        .filter(p => inputPatient.value ? p.RealName.includes(inputPatient.value) : true)
       
})


// 当前选中患者
const currentPatient = ref(null)
const showPatientsTop = ref("请选择患者")
const loading = ref(false) // 添加加载状态



const loadPatientData = async () => {
  loading.value = true
  try {
    // 1. 获取医生ID
    const res = await service.get('/user/getdoctorid?username=bianque')
    const userid = res.data
    const res2 = await service.get('/user/getdeptid?username=bianque')
    const deptid = res2.data

    // 2. 获取该医生的患者列表
    const registerRes = await service.get(`/register/getByUserId?userid=${userid}`)
    const registerRes2 = await service.get(`/register/getByDeptId?deptid=${deptid}`)

    console.log('API响应数据:', registerRes2.data); // 确保这里不是空数组
    console.log('原始API响应:', registerRes2)
    console.log('原始数据样例:', registerRes2.data[0]) // 打印第一条数据
    
     // 3. 数据标准化处理
     allPatients.value = registerRes.data.map(item => {
      // 调试输出原始数据
      console.log('原始数据项:', item)
      
      // 标准化字段（兼容多种命名格式）
      const standardizedItem = {
        // 病历号（兼容驼峰、下划线等格式）
        CaseNumber: item.CaseNumber ?? item.caseNumber ?? item.case_number ?? item.casenumber,
        
        // 姓名（同上）
        RealName: item.RealName ?? item.realName ?? item.real_name ?? item.realname ?? '未知患者',
        
        // 年龄（确保为数字）
        Age: Number(item.Age ?? item.age ?? 0),
        
        // 就诊状态（1=未诊，2=已诊）
        Visitstate: Number(item.Visitstate ?? item.visitState ?? item.visit_state ?? item.visitstate ?? 0),
        
        // 保留原始数据中的所有其他字段
        ...item
      }
      
      // 验证关键字段
      if (!standardizedItem.CaseNumber || standardizedItem.CaseNumber === 'N/A') {
        console.warn('缺少病历号字段:', item)
      }
      
      return standardizedItem
    })

    // 3. 数据标准化处理
    allPatients2.value = registerRes2.data.map(item => {
      // 调试输出原始数据
      console.log('原始数据项:', item)
      
      // 标准化字段（兼容多种命名格式）
      const standardizedItem = {
        // 病历号（兼容驼峰、下划线等格式）
        CaseNumber: item.CaseNumber ?? item.caseNumber ?? item.case_number ?? item.casenumber ?? 'N/A',
        
        // 姓名（同上）
        RealName: item.RealName ?? item.realName ?? item.real_name ?? item.realname ?? '未知患者',
        
        // 年龄（确保为数字）
        Age: Number(item.Age ?? item.age ?? 0),
        
        // 就诊状态（1=未诊，2=已诊）
        // 修改这部分代码
        Visitstate: Number(item.Visitstate ?? item.visitState ?? item.visit_state ?? item.visitstate ?? 0),
        
        // 保留原始数据中的所有其他字段
        ...item
      }
      
      // 验证关键字段
      if (!standardizedItem.CaseNumber || standardizedItem.CaseNumber === 'N/A') {
        console.warn('缺少病历号字段:', item)
      }
      
      return standardizedItem
    })
    
    // 4. 调试输出处理后的数据
    console.log('处理后的患者数据:', allPatients2.value)
    console.log('第一条数据处理结果:', allPatients2.value[0])
    console.log('Visitstate值示例:', allPatients2.value[0]?.Visitstate)
    
    // 5. 显示加载结果
    if (allPatients.value.length === 0) {
      ElMessage.warning('未找到任何患者记录')
    } else {
      ElMessage.success(`成功加载 ${allPatients.value.length} 条患者记录`)
      
      // 打印各状态患者数量（调试用）
      const undiagnosedCount = allPatients.value.filter(p => p.Visitstate === 1).length
      const diagnosedCount = allPatients.value.filter(p => p.Visitstate === 2).length
      console.log(`未诊患者: ${undiagnosedCount} 条，已诊患者: ${diagnosedCount} 条`)
    }
  } catch (error) {
    console.error('加载患者数据失败:', error)
    
    // 更友好的错误提示
    let errorMessage = '加载患者数据失败'
    if (error.response) {
      errorMessage += ` (状态码: ${error.response.status})`
      if (error.response.data?.message) {
        errorMessage += `: ${error.response.data.message}`
      }
    } else {
      errorMessage += `: ${error.message}`
    }
    
    ElMessage.error(errorMessage)
    
    // 开发环境下打印完整错误
    if (process.env.NODE_ENV === 'development') {
      console.error('完整错误信息:', error)
    }
  } finally {
    loading.value = false
  }
}

let ok=ref([]) 


// 修改病历数据结构 - 使用实际存在的字段名
const medicalRecord01 = ref({
    readme: '',      // 主诉
    present: '',     // 现病史
    presenttreat: '',// 现病治疗情况
    history: '',     // 既往史
    allergy: '',     // 过敏史
    physique: '',    // 体格检查
    diagnosis: '',   // 诊断
    proposal: '',    // 检查建议
    careful: ''      // 注意事项
})

// 添加病历加载方法
const loadMedicalRecord = async (casenumber) => {
    if (!casenumber) return


        console.log("请求病历号:", casenumber);
        const res = await service.get(`/api/medicalrecord/getByCaseNumber?casenumber=${casenumber}`)
        
        console.log('完整响应:', res);       // 检查整个响应对象
        console.log('data结构:', res.data);  // 确认data的实际结构
        console.log('字段列表:', Object.keys(res.data)); // 列出所有可用字段
        console.log('readme值:', res.data[0].readme); // 明确测试readme字段
        
        if (res.data) {
            // 将后端数据映射到前端字段
            medicalRecord01.value = {
                readme: res.data[0].readme ,
                present: res.data[0].present ,
                presenttreat: res.data[0].presenttreat || res.data.present_treat ,
                history: res.data[0].history ,
                allergy: res.data[0].allergy ,
                physique: res.data[0].physique ,
                diagnosis: res.data[0].diagnosis ,
                proposal: res.data[0].proposal ,
                careful: res.data[0].careful 
            }
            console.log('赋值后的medicalRecord01:', medicalRecord01.value)
        }
        else {
      console.warn("未找到病历数据");
      
    }
   
}

// 双击患者
const handleDBCurrentChange = (row) => {
    console.log('双击患者:', row)
    currentPatient.value = row
    // 更新显示的患者信息
    showPatientsTop.value = `当前患者：${row.RealName} (病历号: ${row.CaseNumber})`; // 添加这行
    loadMedicalRecord(currentPatient.value.casenumber)
}

// 刷新数据
const reloadUser = () => {
    loadPatientData()
}

// 初始化加载数据
onMounted(() => {
    loadPatientData()
})
</script>